/**
 * Created by yunpeng on 2015/3/26.
 */
angular.module('starter.centerControllers', ['ui.router'])
    .config(function($stateProvider, $urlRouterProvider){
        $stateProvider
            .state('tab.mySuggest' ,{
                url:'/center/mysuggest',
                templateUrl:'view/carrier/center/mysuggest.html',
                controller:'SuggestCtrl'
                ,access: { requiredLogin: true }
            })
            .state('tab.myAuth' ,{
                url:'/center/myauth/:isfrombid',
                templateUrl:'view/carrier/center/auth.html',
                controller:'MyAuthCtrl'
                ,access: { requiredLogin: true }
            })
    })
    .filter('authPostFilter' ,function(){
        return function(input){
            switch (input){
                case 0:return '申 请 认 证';
                case 1:return '已 认 证';
                case 2:return '等 待 审 核'
            }
        }
    })
    .controller('CenterCtrl',function($scope ,$http ,$rootScope ,$state ,$stateParams,CenterService ,AuthenticationService){
        $scope.popQuery1 = false;
        if($stateParams.improve){//判断是否需要完善资料
            $scope.popQuery1 = true;

        }
        $('#pop1button2').click(function(e)
        {
            $scope.popQuery1=false;
            setTimeout(function(){
                $scope.$apply();
            },500);

        });

        $scope.myScroll = new IScroll('#wrapper', { mouseWheel: true  ,click:true});//初始化ISCroll
        document.addEventListener('touchmove', function (e) { e.preventDefault(); }, false);
        $scope.other=true;
        console.log(localStorage.isOther);
        if(localStorage.isOther=='false'){
            $scope.other=false;
        }
        $scope.logout = function(){
            AuthenticationService.isLogged = false;
            localStorage.removeItem('token');
            localStorage.removeItem('user');
            $state.go('/')
        }

        if(!localStorage.user){
            AuthenticationService.isLogged = false;
            localStorage.removeItem('token');
            localStorage.removeItem('user');
            $state.go('/')
        }
        if(JSON.parse(localStorage.user)) {
            var user = $scope.user = JSON.parse(localStorage.user);
            CenterService.getAuthState(user.id).success(function (data, status) {
                $scope.user.carrierauthstate = data.state.carrierauthstate;
            });

            var info = $scope.info = {
                id: user.id
                , company: user.company
                , address: user.address
                , contact: user.contact
                , contactnum: user.contactnum
                , introduce: user.introduce
                ,phone:user.phone
            }
            /*if(user.authstate == 1){
             document.getElementById('info-name').disabled = true;
             }*/
        }

        setTimeout(function(){
            $scope.myScroll.refresh();
        },600);
        $scope.go = function(state){
            $state.go(state);
        }
        $scope.goModifyFace = function(){
            $state.go('tab.cropper',{scale1:1,scale2:1,width:500,height:500,urltype:'upheader'});
        }

        $scope.save =function(){
            var Regx = /[A-Za-z][0-9]|[0-9][A-Za-z]|[A-Za-z]/;
            var Reg=/[A-Za-z][0-9][\u4e00-\u9fa5]|[0-9][A-Za-z][\u4e00-\u9fa5]|[A-Za-z][\u4e00-\u9fa5]|[\u4e00-\u9fa5]/;

            if(info.company==null||info.company==''||info.company.replace(/^[0-9]*$/,'1')==1){
                toast('请正确填写公司名称');
            }else if(info.address==null||info.address==''||info.address.replace(/^[0-9]*$/,'1')==1){
                toast('请正确填写地址');
            }else if(info.contact==null||info.contact==''||info.contact.replace(/^[0-9]*$/,'1')==1){
                toast('请正确填写联系人姓名');
            }else if(info.contactnum==null||info.contactnum==''){
                toast('请正确填写联系人电话');
            }else if(Regx.test(info.contactnum)){
                toast('请正确填写联系人电话');
            }else if(Reg.test(info.contactnum)){
                toast('请正确填写联系人电话');
            }else{

                //var p = phoneEle.value;
                //info.phone=p;
                $http.post('/users/modifyinfo' ,{infoJSON:JSON.stringify(info)})
                    .success(function(data){
                        if(data.err){

                        }else{

                            toast('保存成功')
                            document.getElementById('info-company').blur();
                            document.getElementById('info-contact').blur();
                            document.getElementById('info-contactnum').blur();
                            document.getElementById('info-address').blur();
                            document.getElementById('info-introduce').blur();
                            phoneEle = document.getElementById('info-phone');
                            user.phone = info.phone;;
                            user.company = info.company;
                            user.contact = info.contact;
                            user.contactnum = info.contactnum;
                            user.address = info.address;
                            user.introduce = info.introduce;
                            user.phone = info.phone;
                            localStorage.user = JSON.stringify(user);
                        }
                    })
            }
        }

        //修改手机
        $scope.modifyPhone = function(){
            resume();
            var option = {
                ele:pop
                ,onClose:function(){
                    if(state!=3){
                        if(confirm('操作还没有完成，确定取消吗？')){
                            if(state == 2){
                                phoneEle.value = '';
                            }
                        } else{
                            return false;
                        }
                    }else{
                        state = 2;
                    }
                    codeEle.value = '';
                    code = '';
                    timing = 59;
                    return true;
                }
            }
            popWin(option);
        }
        var pop = document.getElementById('phone-popup');
        var phoneEle = document.getElementById('info-phone');
        var msgEle = document.getElementById('get-msg');
        var msgEle1 = document.getElementById('get-msg1');
        var codeEle = document.getElementById('info-code');
        var err = document.getElementById('phone-error');
        var timeEle = document.getElementById('timing');
        phoneEle.value = user.phone;
        var msging = false;
        var state = 1;
        var msg = '您正在验证您的登录手机号'+user.phone+',验证码为:$$【运车管家】';
        var data = null;
        var code = '';
        var timing = 0;
        msgEle.addEventListener('click' ,function(){
            var p = phoneEle.value.replace(/(^\s*)|(\s*$)/g, "");
            if(p.length != 11){
                //err.innerHTML = '<span style="color:#F74042;">手机号格式不正确</span>';
                showErr('手机号格式不正确')
                phoneEle.focus();
                return;
            }
            if(state == 1){
                data = {
                    username:user.phone
                    ,type:'sendold'
                }
            }else{
                data = {
                    username:p
                    ,type:'modifyphone'
                }
            }
            $http.post('/users/getCode' ,data ,{timeout:8000})
                .success(function(data){
                    if(data=='hasuser'){
                        //err.innerHTML = '<span style="color:#F74042;">该手机号已经被注册</span>'
                        showErr('该手机号已经被注册')
                    }else{
                        //err.innerHTML = data;
                        code = data;
                        showMsg('请输入验证码')
                        //计时器
                        timing = 0;
                        msgEle.style.display = 'none';
                        msgEle1.style.display = 'block';
                        var timer = setInterval(function(){
                            timing ++;
                            timeEle.innerText = 60 - timing ;
                            if(timing >= 60){
                                timing = 0;
                                clearInterval(timer);
                                msgEle.style.display = 'block';
                                msgEle1.style.display = 'none';
                            }
                        } ,1000)
                    }
                })
                .error(function(){

                })
            //code = '111111';showMsg('请输入验证码')

        })
        codeEle.addEventListener('input' ,function(){
            resume(' ');
            if(!code){
                showMsg('请点击获取验证码');
                return;
            }
            var c = codeEle.value;//alert(c);
            if(c.length < 6){
                return;
            }
            if(c!=code){
                showErr('验证码不正确');
            }else{
                timing = 59;
                if(state == 1){
                    code = '';
                    state = 2;
                    resume();
                    phoneEle.disabled = false;
                    phoneEle.value = '';
                    codeEle.value = '';
                }else{
                    showSave();
                }
            }
        })
        phoneEle.addEventListener('input' ,function(){
            //err.innerHTML = '';
            resume();
            code = '';
        })
        function showErr(msg){
            err.innerText = msg;
            err.className = 'phone-error err';
        }
        function showMsg(msg){
            err.innerText = msg;
            err.className = 'phone-error';
        }
        function showSave(){
            err.innerText = '提 交';
            err.className = 'phone-error save';
            err.addEventListener('click' ,savePhone);
        }
        function resume(msg){
            //err.removeEventListener('click' ,savePhone);
            err.className = 'phone-error';
            if(state == 1){
                err.innerText = msg || '请先验证原手机号码';
            }else{
                err.innerText = msg || '请输入您的新手机号码';
            }
        }
        function savePhone(){
            var c = codeEle.value;
            if(!code || c!= code){
                return;
            }
            var ph = phoneEle.value;
            console.log(ph);
            info.phone = ph;
            state = 3;
            resume('验证码正确');
            $scope.info.phone=info.phone;
            //$http.post('/users/modifyinfo' ,{infoJSON:JSON.stringify(data)})
            //    .success(function(data){
            //        if(data.err){
            //
            //        }else{
            //            state = 3;
            //            resume('手机号已经修改成功');
            //            user.phone = p;
            //            localStorage.user = JSON.stringify(user);
            //            //$scope.$apply();
            //        }
            //    }
            //);
        }

        pop.parentNode.removeChild(pop)
        //popWin(pop)
    })
    .controller('MyAuthCtrl',function($scope, $rootScope, $state, $stateParams, CenterService ){
        $scope.myScroll = new IScroll('#wrapper', { mouseWheel: true  ,tap:true});//初始化ISCroll
        document.addEventListener('touchmove', function (e) { e.preventDefault(); }, false);

        var user = $scope.user = JSON.parse(localStorage.user);

        var auth = $scope.auth = CenterService.auth;
        if(user.carrierauthstate == 2 || user.carrierauthstate==1){
            auth = $scope.auth = CenterService.auth = {
                company:user.company
                ,contact:user.contact
                ,contactnum:user.contactnum
                ,idTip:user.idTip
                ,id1Tip:user.id1Tip
            }/*
            document.getElementById('auth-name').disabled = true;
            document.getElementById('auth-idnum').disabled = true;
            document.getElementById('auth-id').disabled = true;*/
        }else{
            if(auth){
                auth.company = auth.company || user.company;
                auth.contact = auth.contact || user.contact;
                auth.contactnum = auth.contactnum || user.contactnum;
            }
            if(!(auth && auth.id==user.id)){
                auth = $scope.auth = CenterService.auth = {
                    id :user.id
                    ,company:user.company
                    ,contact:user.contact
                    ,contactnum:user.contactnum
                    ,licences:null
                    ,roadlicences:null
                    ,idTip:''
                    ,id1Tip:''
                }
            }
        }


        var tip = '上传身份证图片';
        var idFile = document.getElementById('auth-id')
        document.getElementById('auth-id-btn').addEventListener('tap' ,function(e){
            idFile.click()
        } ,false);
        idFile.addEventListener('change' ,function(){
            auth.licences = idFile.files[0];
            var v = this.value;
            if(v){
                v = v.substring(v.lastIndexOf('\\')+1);
            }
            auth.idTip = v ;
            $scope.$apply();
        });
        var id1File = document.getElementById('auth-id1')
        document.getElementById('auth-id1-btn').addEventListener('tap' ,function(e){
            id1File.click()
        } ,false);
        id1File.addEventListener('change' ,function(){
            auth.roadlicences = id1File.files[0];
            var v = this.value;
            if(v){
                v = v.substring(v.lastIndexOf('\\')+1);
            }
            auth.id1Tip  = v ;
            $scope.$apply();
        });

        //提交认证表单
        $scope.busy = false;
        document.getElementById('auth-post').addEventListener('tap' ,function(){
            if(user.authstate == 1 || $scope.busy)return;
            if(!auth.company){//用户名必填
                toast('请输入公司名称');
                document.getElementById('auth-company').focus();
                return;
            }
            if(!auth.licences){
                toast('请选择营业执照');
                return;
            }
            if(!auth.roadlicences){
                toast('请选择道路运输许可证');
                return;
            }
            if(!auth.contact){//用户名必填
                toast('请输入联系人姓名');
                document.getElementById('auth-contact').focus();
                return;
            }
            if(!auth.contactnum){//用户名必填
                toast('请输入联系电话');
                document.getElementById('auth-contactnum').focus();
                return;
            }
            var data = new FormData();
            data.append('id' ,user.id);
            data.append('company' ,auth.company);
            data.append('contact' ,auth.contact);
            data.append('contactnum' ,auth.contactnum);
            data.append('licences' ,auth.licences);
            data.append('roadlicences' ,auth.roadlicences);
            var params = {
                data:data
                ,url:'/users/carrierauth'
            }
            CenterService.postFileForm(params ,$scope ,function(data){
                if(!data.err){
                    //alert('资料已上传，请等待人工审核');
                    $scope.busy = false;
                    user.authstate = 2;
                    user.contact = auth.contact;
                    user.company = auth.company;
                    user.contactnum = auth.contactnum;
                    user.idTip = auth.idTip;
                    user.id1Tip = auth.id1Tip;
                    $scope.$apply();
                    localStorage.user = JSON.stringify(user);

                    if($stateParams.isfrombid){
                        $state.go('tab.bidding', $rootScope.bidobj);//返回到竞价页面
                    }

                }
            })
        })

        $scope.error = '';
        $scope.loadingTip = '';
        function toast(msg){
            $scope.error = msg;
            $scope.$apply();
            setTimeout(function(){
                $scope.error = '';
                $scope.$apply();
            } ,3000)
        }

        //首次加载页面，刷新iScroll
        setTimeout(function(){
            $scope.myScroll.refresh();
        },600);
    })
    .controller('MyInfoCtrl',function($scope ,$http ,CenterService){
        $scope.myScroll = new IScroll('#wrapper', { mouseWheel: true  ,click:true});//初始化ISCroll
        document.addEventListener('touchmove', function (e) { e.preventDefault(); }, false);


        var user =  $scope.user = JSON.parse(localStorage.user);
        var info = $scope.info = CenterService.info;
        if(!(info && info.id==user.id)){
            info = $scope.info = CenterService.info = {
                id:user.id
                ,nickname:user.nickname
                ,address:user.address
                ,introduce:user.introduce
            }
        }else{
            info.nickname = info.nickname || user.nickname;
            info.address = info.address || user.address;
            info.introduce = info.introduce || user.introduce;
        }

        $scope.post = function(){
            if(!(info.nickname && info.address && info.introduce)){
                return;
            }
            $http.post('/users/modifyinfo' ,{infoJSON:JSON.stringify(info)})
                .success(function(data){
                    if(data.err){
                        alert('网络连接失败，请稍候再试')
                    }else{
                        user.nickname = info.nickname;
                        user.address = info.address;
                        user.introduce = info.introduce;
                        localStorage.user = JSON.stringify(user);
                        alert('已经保存成功')
                    }
                })
        }
    })
    .controller('SuggestCtrl' ,function($scope ,$http ,CenterService){
        $scope.myScroll = new IScroll('#wrapper', { mouseWheel: true  ,click:true});//初始化ISCroll
        document.addEventListener('touchmove', function (e) { e.preventDefault(); }, false);

        var user = $scope.user = JSON.parse(localStorage.user);
        var suggest = $scope.suggest = CenterService.suggest;
        if(!(suggest&&suggest.userid==user.id)){
            suggest = CenterService.suggest = $scope.suggest = {
                userid:user.id
                ,content:''
            }
        }

        setTimeout(function(){
            $scope.myScroll.refresh();
        },600);

        $scope.post = function(){
            //suggest.content = suggest.content.replace(/(^\s*)|(\s*$)/g, "");
            document.getElementById('suggest-content').value = suggest.content;
            if(!suggest.content){
                document.getElementById('suggest-content').focus();
                return;
            }
            $http.post('/users/suggest' ,{suggestJSON:JSON.stringify(suggest)})
                .success(function(data){
                    if(data.err){
                        alert('网络连接出错，请稍候再试')
                    }else{
                        alert('建议已经提交成功！')
                        suggest.content = '';
                    }
                })
        }
    });


function popWin(option){
    var ele = option.ele;
    var wHeight = window.innerHeight;
    var wWidth = window.innerWidth;
    var wrapper = document.createElement("div");
    document.body.appendChild(wrapper);
    wrapper.style.position = 'fixed';
    wrapper.style.top = 0;
    wrapper.style.left = 0;
    wrapper.style.width = wWidth+'px';
    wrapper.style.height = wHeight+100+'px';
    wrapper.style.background = 'rgba(100,100,100,0)';
    wrapper.style.zIndex = 9999;
    var inner = document.createElement("div");
    wrapper.appendChild(inner);
    inner.appendChild(ele);
    var top = wHeight*0.5 - ele.offsetHeight*0.7 ;
    if(top < 60){
        top = 60;
    }
    var left = wWidth*0.5 - ele.offsetWidth*0.5 ;
    inner.style.position = 'absolute';
    inner.style.top = top+'px';
    inner.style.left = left+'px';
    var btnClose = document.createElement('div');
    inner.appendChild(btnClose);
    btnClose.style.position = 'absolute';
    btnClose.style.top = '-4px';
    btnClose.style.right = '-4px';
    btnClose.innerText = "×";
    btnClose.style.fontSize = '16px';
    btnClose.style.lineHeight = '1';
    btnClose.style.borderRadius = '50%';
    btnClose.style.padding = '2px 5px';
    btnClose.style.color = 'white';
    btnClose.style.background = '#666';

    btnClose.addEventListener('click' ,function(e){
        if(!option.onClose()){
            return;
        }
        document.body.removeChild(wrapper);
    })
}